package com.qianchang.microfinance.view.credit.data;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.dm.library.adapter.CommonAdapter;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.BitmapUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.AttachmentListBean;
import com.qianchang.microfinance.bean.MaterialImageBean;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.ImageChoseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: zhoulai
 * 修改时间: 2017/7/21 14:02
 */


public class CompleteMaterialDetailActivity extends ImageChoseActivity implements CommonAdapter.OnItemClickListener {

    private static final String TAG = "CompleteMaterialDetail";
    public static final String MATERIAL_BEAN = "material_bean";

    @BindView(R.id.recycler_photo)
    RecyclerView recyclerPhoto;
    @BindView(R.id.btn_commit)
    DButton btnCommit;
    @BindView(R.id.iv_example)
    ImageView ivExample;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tv_tips)
    DTextView tvTips;
    @BindView(R.id.tv_desc)
    DTextView tvDesc;
    private ArrayList<ImageItem> materialPhotoList = new ArrayList<>();
    private ArrayList<String> fileIdList = new ArrayList<>();
    private CompleteMaterialDetailAdapter mAdapter;
    //    private int isAuth;
    private static final int maxImages = 8;
    private String currentId;
    private String productType;
    private String dataID;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete_material_detail);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        Bundle bundle = getBundle();
        if (null != bundle) {
            AttachmentListBean attachmentListBean = (AttachmentListBean) bundle.getSerializable(MATERIAL_BEAN);
            currentId = bundle.getString(ConfirmInfoJinbaoActivity.CURRENT_ID);
            if (null != attachmentListBean) {
//                isAuth = attachmentListBean.getIsAuth();
                productType = attachmentListBean.getProductType();
                dataID = attachmentListBean.getId();
                setTitleName(attachmentListBean.getName());
                String exampleUrl = attachmentListBean.getExampleUrl();
                Glide.with(this.getApplicationContext()).load(DMConstant.Config.BASE_URL + exampleUrl).error(R.drawable.img_jzsb).into(ivExample);
            } else {
                attachmentListBean = new AttachmentListBean();
            }
        }
//        if (0 == isAuth) {
//            isAuth = 1;
//        } else {
//            isAuth = 0;
//        }
//        MyDataStatus.setBtnStatus(isAuth, btnCommit);

        setMaxImageCount(maxImages);
        setImages(materialPhotoList);
        mAdapter = new CompleteMaterialDetailAdapter(this, materialPhotoList);
        recyclerPhoto.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerPhoto.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setShowAdd(isCanAdd());
        mAdapter.setOnDeleteListener(new CompleteMaterialDetailAdapter.OnDeleteClick() {
            @Override
            public void onDelete(ImageItem imageItem) {
                showExample();
//                commitAble();
                isCanAdd();
                if (null != imageItem) {
                    String fileId = imageItem.getFileId();
                    if (null != fileIdList && fileIdList.contains(fileId)) {
                        fileIdList.remove(fileId);
                    }
                }
            }
        });
    }

    @Override
    public void initImagePickerForSelectPhoto(int selectedImageSize) {
        super.initImagePickerForSelectPhoto(selectedImageSize);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
    }

    @Override
    protected void initData() {
        super.initData();
        findAttachmentInfo();
    }

    private void refreshUi() {
        setImages(materialPhotoList);
        mAdapter.notifyDataSetChanged();
        showExample();
        isCanAdd();
        commitAble();
    }


    /**
     * 获取服务器文件数据
     */
    private void findAttachmentInfo() {
        HttpParams params = new HttpParams();
        params.put("dataId", dataID);
        params.put("projectId", currentId);
        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_USER_ATTACH_ADDR, params, new RequestCallBack<ArrayList<MaterialImageBean>>() {
            @Override
            public void onSuccess(JsonResult<ArrayList<MaterialImageBean>> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ArrayList<MaterialImageBean> imageBeanArrayList = response.getObject();
                    if (null != imageBeanArrayList) {
                        //1.获取服务器的文件
                        for (MaterialImageBean materialImageBean : imageBeanArrayList) {
                            ImageItem imageItem = new ImageItem();
                            imageItem.setPath(DMConstant.Config.BASE_URL + materialImageBean.getFileUrl());
                            imageItem.setFileId(materialImageBean.getFileId());
                            fileIdList.add(materialImageBean.getFileId());
                            materialPhotoList.add(imageItem);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                    refreshUi();
                } else {
                    ToastUtil.getInstant().show(CompleteMaterialDetailActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(CompleteMaterialDetailActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    private void commit() {
        HashMap<String, String> params = new HashMap<>();
        params.put("fileType", "0");
        params.put("isTransform", "false");
        HashMap<String, File> files = new HashMap<>();
        for (int i = 0; i < materialPhotoList.size(); i++) {
            ImageItem imageItem = materialPhotoList.get(i);
            File file = new File(imageItem.path);
            if (file.exists()) {
                String path = BitmapUtils.createFile(this, imageItem.path);
                if (null != path) {
                    File upFile = new File(path);
                    if (upFile.exists()) {
                        String imageName = i + upFile.getName();
                        files.put(imageName, upFile);
                    }
                }
            }
        }
        show();
        if (files.isEmpty()) {
            //说明上传的文件为空
            uploadAttachList(null);
        } else {
            //说明有上传的图片
            DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.UPLOAD_FILE_BASIC_INFO, params, "uploadFile", files, new RequestCallBack<ArrayList<UploadFileBean>>() {
                @Override
                public void onSuccess(JsonResult<ArrayList<UploadFileBean>> response) {
                    if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                        ArrayList<UploadFileBean> uploadFileList = response.getObject();
                        uploadAttachList(uploadFileList);
                    } else {
                        dismiss();
                        ToastUtil.getInstant().show(CompleteMaterialDetailActivity.this, response.getDescription());
                    }
                }

                @Override
                public void onFailure(String msg) {
                    dismiss();
                    ToastUtil.getInstant().show(CompleteMaterialDetailActivity.this, msg);
                }

                @Override
                public void onConnectFailure(String msg) {

                }
            });
        }
    }


    /**
     * 上传附件图片ID
     */
    private void uploadAttachList(ArrayList<UploadFileBean> uploadFileList) {
        StringBuilder sb = new StringBuilder();
        if (null != uploadFileList) {
            for (UploadFileBean uploadFileBean : uploadFileList) {
                fileIdList.add(uploadFileBean.getId());
            }
        }
        if (null == fileIdList || fileIdList.isEmpty()) {
            dismiss();
            ToastUtil.getInstant().show(this, "请至少选择一张图片");
            return;
        }
        for (String photoId : fileIdList) {
            sb.append(photoId).append(",");
        }
        if (!sb.toString().isEmpty()) sb.deleteCharAt(sb.length() - 1);
        HttpParams params = new HttpParams();
        params.put("dataId", dataID);
        params.put("userAttachId", sb.toString());
        params.put("projectId", currentId);
        params.put("attachType", productType);

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.UPLOAD_FILES, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    finish();
                } else {
                    ToastUtil.getInstant().show(CompleteMaterialDetailActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(CompleteMaterialDetailActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    @Override
    public void onItemClick(View v, int position) {
        if (isCanAdd() && position == materialPhotoList.size()) {
            //添加图片
            showSelectPhotoDialog();
        } else {
            //TODO 查看图片
        }
    }


    @Override
    public void onPhotoResult(ArrayList<ImageItem> imageItems, int flag) {
        mAdapter.setShowAdd(isCanAdd());
        showExample();
        commitAble();
    }

    /**
     * 添加文件按钮是否可用
     */
    private boolean isCanAdd() {
//        boolean canAdd;
//        if (materialPhotoList != null && materialPhotoList.size() >= maxImages) {
//            canAdd = false;
//        } else {
//            switch (isAuth) {
//                case MyDataStatus.YTJ:
//                    canAdd = false;
//                    break;
//                case MyDataStatus.QRZ:
//                    canAdd = true;
//                    break;
//                default:
//                    canAdd = true;
//                    break;
//            }
//        }
        return true;
    }

    @OnClick({R.id.iv_example, R.id.iv_add, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_example:
                break;
            case R.id.iv_add:
                showSelectPhotoDialog();
                break;
            case R.id.btn_commit:
                if (checkClick(R.id.btn_commit)) {
                    commit();
                }
                break;
        }
    }

    public void showExample() {
        if (null != materialPhotoList && materialPhotoList.size() > 0) {
            llContent.setVisibility(View.GONE);
            recyclerPhoto.setVisibility(View.VISIBLE);
        } else {
            llContent.setVisibility(View.VISIBLE);
            recyclerPhoto.setVisibility(View.GONE);
        }
    }

    public void commitAble() {
        if (materialPhotoList != null && materialPhotoList.size() > 0) {
            btnCommit.setEnabled(true);
        } else {
            btnCommit.setEnabled(false);
        }
    }
}
